import React, { useRef, useEffect, useState } from 'react';
import { PoseController } from '@/lib/mediapipe/pose';
import { drawStylizedPose } from '@/lib/mediapipe/drawing';

interface PoseCanvasProps {
  width?: number;
  height?: number;
  onPoseDetected?: (pose: any) => void;
}

const PoseCanvas: React.FC<PoseCanvasProps> = ({ 
  width = 400, 
  height = 300, 
  onPoseDetected 
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const videoRef = useRef<HTMLVideoElement>(null);
  const controllerRef = useRef<PoseController | null>(null);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  
  useEffect(() => {
    const initialize = async () => {
      const canvas = canvasRef.current;
      const video = videoRef.current;
      if (!canvas || !video) return;

      const canvasCtx = canvas.getContext('2d');
      if (!canvasCtx) return;

      try {
        // 延迟以等待 index.html 的全局脚本加载完成
        await new Promise((r) => setTimeout(r, 400));

        controllerRef.current = new PoseController(video, {
          width,
          height,
          onResults: (results: any) => {
            canvasCtx.save();
            canvasCtx.clearRect(0, 0, canvas.width, canvas.height);

            canvasCtx.save();
            // 镜像翻转，提升直觉交互
            canvasCtx.scale(-1, 1);
            canvasCtx.translate(-canvas.width, 0);
            canvasCtx.drawImage(results.image, 0, 0, canvas.width, canvas.height);
            canvasCtx.restore();

            if (results.poseLandmarks) {
              canvasCtx.save();
              canvasCtx.scale(-1, 1);
              canvasCtx.translate(-canvas.width, 0);

              drawStylizedPose(canvasCtx, results.poseLandmarks, canvas.width, canvas.height, {
                visibilityThreshold: 0.2,
                lineWidth: Math.max(canvas.width, canvas.height) * 0.012,
                pointRadius: Math.max(canvas.width, canvas.height) * 0.018,
              });

              canvasCtx.restore();

              if (onPoseDetected) onPoseDetected(results.poseLandmarks);
            }

            canvasCtx.restore();
          },
        });

        await controllerRef.current.start();
        setErrorMessage(null);
      } catch (err: any) {
        console.error(err);
        setErrorMessage(err?.message ?? 'AI 姿态识别初始化失败');
      }
    };

    initialize();

    return () => {
      if (controllerRef.current) {
        controllerRef.current.dispose();
        controllerRef.current = null;
      }
    };
  }, [width, height, onPoseDetected]);
  
  return (
    <div className="relative">
      <video
        ref={videoRef}
        className="hidden"
        width={width}
        height={height}
        autoPlay
        muted
        playsInline
      />
      <canvas
        ref={canvasRef}
        className="pose-canvas"
        width={width}
        height={height}
      />
      <div className="absolute inset-0 pointer-events-none bg-gradient-to-br from-transparent via-white/5 to-white/10" />
      <div className="absolute top-2 left-2 bg-black/50 text-white px-2 py-1 rounded-lg text-xs">
        {errorMessage ? 'AI 初始化失败' : 'AI 姿态识别'}
      </div>
    </div>
  );
};

export default PoseCanvas;